package cn.z2huo.knowledge.concurrency.producerconsumer;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>数据缓冲区
 *
 * @author z2huo
 */
class NotSafeDataBuffer<T> {

    /**
     * 队列中同时存在元素的最大数量
     */
    private static final int MAX_AMOUNT = 10;

    private final List<T> dataList = new LinkedList<>();

    /**
     * 当前队列中存在元素数量
     */
    private final AtomicInteger amount = new AtomicInteger(0);

    /**
     * 向数据区域添加元素
     * @param element   待添加元素
     */
    public synchronized void add(T element) {

        if (amount.get() >= MAX_AMOUNT) {
            System.out.println("队列已满");
            return;
        }

        dataList.add(element);
        System.out.println("add element, element is " + element);
        amount.incrementAndGet();

        if (amount.get() != dataList.size()) {
            throw new RuntimeException("数据不一致, " + amount + " != " + dataList.size());
        }
    }

    /**
     * 从数据区域中取出一个元素
     */
    public synchronized T fetch() {
        if (amount.get() <= 0) {
            System.out.println("队列已空");
            return null;
        }
        T element = dataList.remove(0);
        System.out.println("fetch element, element is " + element);
        amount.decrementAndGet();
        if (amount.get() != dataList.size()) {
            throw new RuntimeException("数据不一致, " + amount + " != " + dataList.size());
        }
        return element;
    }

}
